﻿using Apewer;
using Apewer.Internals;
using Apewer.Source;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Apewer.Network
{

    /// <summary>邮件。</summary>
    public sealed class MailMessage : IToJson
    {

        private MailAddress _sender = null;

        private List<MailAddress> _receiver = new List<MailAddress>();

        private List<MailAddress> _carboncopy = new List<MailAddress>();

        private List<MailAddress> _blindcarboncopy = new List<MailAddress>();

        private Dictionary<string, byte[]> _attachment = new Dictionary<string, byte[]>();

        private string _title = Constant.EmptyString;

        private string _content = Constant.EmptyString;

        private Encoding _encoding = Encoding.UTF8;

        private bool _html = false;

        private MailPriority _priority = MailPriority.Normal;

        /// <summary>构造函数。</summary>
        public MailMessage() { }

        /// <summary>编码，默认为 UTF-8。</summary>
        public Encoding Encoding { get { return _encoding; } set { _encoding = value ?? Encoding.UTF8; } }

        /// <summary>附件。</summary>
        public Dictionary<string, byte[]> Attachment { get { return _attachment; } }

        /// <summary>发件人。</summary>
        public MailAddress Sender { get { return _sender; } set { _sender = value ?? new MailAddress(); } }

        /// <summary>收件人。</summary>
        public List<MailAddress> Receiver { get { return _receiver; } }

        /// <summary>抄送。</summary>
        public List<MailAddress> CarbonCopy { get { return _carboncopy; } }

        /// <summary>密送。</summary>
        public List<MailAddress> BlindCarbonCopy { get { return _blindcarboncopy; } }

        /// <summary>主题/标题。</summary>
        public string Title { get { return _title; } set { _title = TextUtility.Trim(value, true); } }

        /// <summary>正文/内容。</summary>
        public string Content { get { return _content; } set { _content = value ?? Constant.EmptyString; } }

        /// <summary>使用 HTML 格式，默认为 FALSE 值。</summary>
        public bool Html { get { return _html; } set { _html = value; } }

        /// <summary>优先级。</summary>
        public MailPriority Priority { get { return _priority; } set { _priority = value; } }

        /// <summary>获取 JSON 文本。</summary>
        public override string ToString()
        {
            return ToJson().ToString();
        }

        /// <summary>获取 JSON 对象。</summary>
        public Json ToJson()
        {
            var json = Json.NewObject();

            json["Priority"] = Priority.ToString();
            json["Encoding"] = Encoding.ToString();
            json["Title"] = Title;
            json["Content"] = Content;
            json["Html"] = Html.ToString();

            json.SetProperty("Sender", Json.From(Sender));

            var receiver = Json.NewArray();
            foreach (var account in _receiver) receiver.AddItem(Json.From(account));
            json.SetProperty("Receiver", receiver);

            var cc = Json.NewArray();
            foreach (var account in _carboncopy) receiver.AddItem(Json.From(account));
            json.SetProperty("CarbonCopy", cc);

            var bcc = Json.NewArray();
            foreach (var account in _blindcarboncopy) receiver.AddItem(Json.From(account));
            json.SetProperty("BlindCarbonCopy", bcc);

            var attachment = Json.NewArray();
            foreach (var kvp in _attachment)
            {
                var item = Json.NewObject();
                item["Name"] = TextUtility.Trim(kvp.Key);
                item["Base64"] = BytesUtility.ToBase64(kvp.Value);
                attachment.AddItem(item);
            }
            json.SetProperty("Attachment", attachment);

            return json;
        }

        internal System.Net.Mail.MailMessage ToInstance()
        {
            var mm = new System.Net.Mail.MailMessage();

#if !NET20
            mm.HeadersEncoding = _encoding;
#endif
            mm.SubjectEncoding = _encoding;
            mm.BodyEncoding = _encoding;


            if (_sender != null)
            {
                var ma = _sender.ToInstance(_encoding);
                if (ma != null) mm.From = ma;
            }

            foreach (var account in _receiver)
            {
                if (account == null) continue;
                var ma = account.ToInstance(_encoding);
                if (ma != null) mm.To.Add(ma);
            }

            foreach (var account in _carboncopy)
            {
                if (account == null) continue;
                var ma = account.ToInstance(_encoding);
                if (ma != null) mm.CC.Add(ma);
            }

            foreach (var account in _blindcarboncopy)
            {
                if (account == null) continue;
                var ma = account.ToInstance(_encoding);
                if (ma != null) mm.Bcc.Add(ma);
            }

            foreach (var attachment in _attachment)
            {
                var a = GetAttachment(attachment.Key, attachment.Value, _encoding);
                mm.Attachments.Add(a);
            }

            mm.Subject = _title;
            mm.Body = _content;
            mm.IsBodyHtml = _html;

            return mm;
        }

        private static System.Net.Mail.Attachment GetAttachment(string name, byte[] bytes, Encoding encoding)
        {
            if (TextUtility.IsBlank(name)) return null;

            var data = bytes;
            var memory = new MemoryStream();
            if (data != null)
            {
                if (data.Length > 0) memory.Write((byte[])data);
            }
            memory.ResetPosition();

            var attachment = new System.Net.Mail.Attachment(memory, TextUtility.Trim(name));
            attachment.NameEncoding = encoding;

            return attachment;
        }

    }

}
